import { _decorator, Asset, Component, instantiate, isValid, Node, Prefab, resources } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('DyAssetsManager')
export class DyAssetsManager {
    private static _instance: DyAssetsManager = null;
    public static get instance(): DyAssetsManager {
        if (!DyAssetsManager._instance) {
            DyAssetsManager._instance = new DyAssetsManager();
        }
        return DyAssetsManager._instance;
    }

    private _assetsMap: Map<string, Asset> = new Map();

    constructor() {
        DyAssetsManager._instance = this;
    }

    public static createPrefab(path: string, cb: (node: Node) => void): void {
        resources.load(path, Prefab, (err, prefb) => {
            if (err) {
                console.error(err);
                return;
            }
            const obj = this.instantiatePrefab(prefb);
        })
    }

    public static async createPrefabAsync(path: string) : Promise<Node>
    {
        return new Promise<Node>((resolve, reject) => {
            resources.load(path, Prefab, (err, prefb) => {
                if (err) {
                    reject(err);
                    return;
                }
                const obj = this.instantiatePrefab(prefb);
                resolve(obj);
            })
        })
    }

    public static instantiatePrefab(prefab: Prefab): Node {
        let node = instantiate(prefab);
        prefab.addRef();
        return node;
    }

    //TODO: 实例化Node节点,资源引用计数额外处理
    public static instantiateNode(node: Node): Node {
        let res = instantiate(node);
        if (node['prefab']) {
            let prefb = node['prefab'];
            if (prefb.asset) {
                prefb.asset.addRef();
            }
        }
        return res;
    }

    public static Destroy(node: Node): void {
        console.log('onNodeDestroyed =>', node);
        try {
            if (isValid(node)) {
                if (node['prefab']) {
                    let prefb = node['prefab'];
                    if (prefb.asset) {
                        prefb.asset.decRef();
                    }
                }
                node.destroy();
            }
        } catch (error) {
            console.log(error);
        }
    }

}


